/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets.faculty;

import org.apache.commons.fileupload.*;
import java.io.File;
import java.sql.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author FRIENDS
 */
@WebServlet(name = "uploadma", urlPatterns = {"/faculty/classes/uploadma"})
public class uploadma extends HttpServlet {

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        
        String courseid=null,desc=null,filename=null,contentType=null;
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		//System.out.println("request: "+request);
		if (!isMultipart) {
			//System.out.println("File Not Uploaded");
                                    }
                else {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = null;

			try {
				items = upload.parseRequest(request);
				//System.out.println("items: "+items);
			} catch (FileUploadException e) {
				//e.printStackTrace();
			}
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField())
                                {
				if(item.getFieldName().equals("courseid"))	
                                    {
                                     courseid=item.getString();
                                    }
                                else if(item.getFieldName().equals("description"))
                                {
                                    desc=item.getString();
                                }
				}
                               
                                else 
                                {
                                    filename=item.getName();
                                    contentType=item.getContentType();
                                    filename=filename.substring(filename.lastIndexOf("\\")+1);
                                   try{ item.write(new File(getServletContext().getRealPath("/uploads"),filename));}catch(Exception e){}
                                    
                                }
                        }
                        try{
//System.out.println("add agent");
	PreparedStatement pst=null;
	Statement st=null;
	ResultSet rs=null;
	pst=dbconnector.DBDriver.getPrepare("insert into coursecontent values (?,?,null,?,?)");
        pst.setString(1, courseid);
        pst.setString(2, desc);
        pst.setString(3, ((AO.Login)request.getSession().getAttribute("logindata")).getUserid());   
        pst.setString(4, filename);
        int result=pst.executeUpdate();
//System.out.println("values inserted");

			if(result>0)
	{
			response.sendRedirect("showcourses.jsp?status=0");
	}
	else
	{
		//response.sendRedirect("postma.jsp?message=<font color=red>not added,please try again!!</font>");
	}
			

}catch(Exception e){
			  System.out.println(e);
		  }
    finally {
     // pst.close();
      //fis.close();
	}
                }
        
        
                /*  response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String courseid=request.getParameter("courseid");
        String description=request.getParameter("description");
        
        System.out.println(courseid);
        System.out.println(description);
        String contentType = request.getContentType();
System.out.println("Content type is  : " +contentType);

if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
{
	System.out.println("in if loop");

DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
System.out.println("1");
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength)
{
//System.out.println("In while");
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
String saveFile1 = file.substring(file.indexOf("filename=\"") + 10);
//out.print("FileName:" + saveFile.toString());
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile1 = saveFile1.substring(0, saveFile1.indexOf("\n"));
//out.print("FileName:" + saveFile.toString());
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
saveFile1 = saveFile1.substring(saveFile1.lastIndexOf("\\") + 1,saveFile1.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());

int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
String path=getServletContext().getRealPath("/Files");
System.out.println(path);
System.out.println(saveFile);
String FileName=saveFile;
String fname=saveFile;
saveFile = path +"\\"+ saveFile;
System.out.println("1: "+saveFile);



FileOutputStream fileOut = new FileOutputStream(saveFile);

fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();


try{
System.out.println("add agent");
	PreparedStatement pst=null;
	Statement st=null;
	ResultSet rs=null;
	pst=dbconnector.DBDriver.getPrepare("insert into coursecontent values (?,?,null,?,?)");
        pst.setString(1, courseid);
        pst.setString(2, description);
        pst.setString(3, ((AO.Login)request.getSession().getAttribute("logindata")).getUserid());   
        pst.setString(4, FileName);
        int result=pst.executeUpdate();
System.out.println("values inserted");

			if(result>0)
	{
			response.sendRedirect("showcourses.jsp?status=0");
	}
	else
	{
		//response.sendRedirect("postma.jsp?message=<font color=red>not added,please try again!!</font>");
	}
			

}catch(Exception e){
			  System.out.println(e);
		  }
    finally {
     // pst.close();
      //fis.close();
	}
        
	/*pst=MyDriver.getPrepare("insert into postmrp (mrpid,mrp,ptech,title,file,postedon,userid,like1,unlike) values(null,?,?,?,?,null,?,0,0 )");
	System.out.println(" taking details ");
		
            
			pst.setString(1,mrp);
			pst.setString(2,ptech);
			pst.setString(3,title);
		
			pst.setString(4,FileName);
			pst.setString(5,userid);
		
	System.out.println(" took values ");
            int result=pst.executeUpdate();
System.out.println("values inserted");

			if(result>0)
	{
			response.sendRedirect("postma.jsp?message=<font color=#3366CC>Your File Posted Successfully</font>");
	}
	else
	{
		response.sendRedirect("postma.jsp?message=<font color=red>not added,please try again!!</font>");
	}
			

}catch(Exception e){
			  System.out.println(e);
		  }
    finally {
     // pst.close();
      //fis.close();
	}
}
	
   */
    
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
